<script lang="ts" setup>
import { computed, reactive, ref, watch } from 'vue';

import {
  Button,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Modal,
  Select,
  SelectOption,
  Switch,
  TabPane,
  Tabs,
  Textarea,
} from 'ant-design-vue';

import {
  createCapabilityInstance,
  updateCapabilityInstance,
} from '#/api/resource-center';

// Props
const props = defineProps<{
  instance?: any;
  visible: boolean;
}>();

// Emits
const emit = defineEmits<{
  success: [];
  'update:visible': [value: boolean];
}>();

// 响应式数据
const formRef = ref();
const submitting = ref(false);
const activeConfigTab = ref('basic');
const jsonConfig = ref('');

// 表单数据
const formData = reactive({
  name: '',
  resourceId: '',
  capabilityId: '',
  status: 'enabled',
  configuration: {},
});

// 基础配置
const basicConfig = reactive({
  maxBookingDays: 30,
  allowOverbooking: false,
  autoConfirm: true,
  supportedMethods: ['alipay', 'wechat'],
  maxAmount: 10_000,
  currency: 'CNY',
  channels: ['sms', 'email'],
  retryCount: 3,
  timeout: 5000,
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入实例名称', trigger: 'blur' }],
  resourceId: [{ required: true, message: '请输入资源ID', trigger: 'blur' }],
  capabilityId: [
    { required: true, message: '请选择能力类型', trigger: 'change' },
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
};

// 计算属性
const isEdit = computed(() => {
  return !!props.instance;
});

// 获取配置标签
const getConfigLabel = (key: string) => {
  const labelMap = {
    maxBookingDays: '最大预订天数',
    allowOverbooking: '允许超订',
    autoConfirm: '自动确认',
    supportedMethods: '支持的支付方式',
    maxAmount: '最大金额',
    currency: '货币类型',
    channels: '通知渠道',
    retryCount: '重试次数',
    timeout: '超时时间(ms)',
  };
  return labelMap[key] || key;
};

// 获取配置选项
const getConfigOptions = (key: string) => {
  const optionsMap = {
    supportedMethods: ['alipay', 'wechat', 'card', 'cash'],
    currency: ['CNY', 'USD', 'EUR', 'JPY'],
    channels: ['sms', 'email', 'push', 'wechat'],
  };
  return optionsMap[key] || [];
};

// 能力类型变化处理
const onCapabilityChange = (value: string) => {
  // 根据能力类型设置默认配置
  const defaultConfigs = {
    booking_capability: {
      maxBookingDays: 30,
      allowOverbooking: false,
      autoConfirm: true,
    },
    payment_capability: {
      supportedMethods: ['alipay', 'wechat'],
      maxAmount: 10_000,
      currency: 'CNY',
    },
    notification_capability: {
      channels: ['sms', 'email'],
      retryCount: 3,
      timeout: 5000,
    },
    report_capability: {
      maxRows: 10_000,
      exportFormats: ['excel', 'pdf'],
      cacheTime: 3600,
    },
  };

  const config = defaultConfigs[value] || {};
  Object.assign(basicConfig, config);
  updateJsonConfig();
};

// 更新JSON配置
const updateJsonConfig = () => {
  jsonConfig.value = JSON.stringify(basicConfig, null, 2);
};

// 监听JSON配置变化
watch(jsonConfig, (newValue) => {
  try {
    const parsed = JSON.parse(newValue);
    Object.assign(basicConfig, parsed);
  } catch {
    // JSON格式错误时不更新
  }
});

// 监听visible变化
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      initializeForm();
    }
  },
);

// 初始化表单
const initializeForm = () => {
  if (props.instance) {
    // 编辑模式
    Object.assign(formData, {
      name: props.instance.name,
      resourceId: props.instance.resourceId,
      capabilityId: props.instance.capabilityId,
      status: props.instance.status,
    });

    // 初始化配置
    if (props.instance.configuration) {
      Object.assign(basicConfig, props.instance.configuration);
      updateJsonConfig();
    }
  } else {
    // 新建模式
    Object.assign(formData, {
      name: '',
      resourceId: '',
      capabilityId: '',
      status: 'enabled',
    });

    // 重置配置
    Object.assign(basicConfig, {
      maxBookingDays: 30,
      allowOverbooking: false,
      autoConfirm: true,
      supportedMethods: ['alipay', 'wechat'],
      maxAmount: 10_000,
      currency: 'CNY',
      channels: ['sms', 'email'],
      retryCount: 3,
      timeout: 5000,
    });
    updateJsonConfig();
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();
    submitting.value = true;

    // 构建提交数据
    const submitData = {
      ...formData,
      configuration: { ...basicConfig },
    };

    if (props.instance) {
      submitData.id = props.instance.id;
    }

    // 调用API
    let result;
    result = await (isEdit.value
      ? updateCapabilityInstance(props.instance.id, submitData)
      : createCapabilityInstance(submitData));

    if (result.code === 200) {
      message.success('保存成功');
      emit('success');
      handleCancel();
    } else {
      throw new Error('保存失败');
    }
  } catch (error) {
    console.error('保存失败:', error);
    message.error(`保存失败: ${(error as Error).message}`);
  } finally {
    submitting.value = false;
  }
};

// 取消
const handleCancel = () => {
  emit('update:visible', false);
};
</script>

<template>
  <Modal
    :visible="visible"
    :title="isEdit ? '编辑能力实例' : '新建能力实例'"
    width="600px"
    :footer="null"
    :destroy-on-close="true"
    @update:visible="(val) => emit('update:visible', val)"
  >
    <Form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      layout="horizontal"
    >
      <FormItem label="实例名称" name="name">
        <Input v-model="formData.name" placeholder="请输入实例名称" />
      </FormItem>

      <FormItem label="资源ID" name="resourceId">
        <Input v-model="formData.resourceId" placeholder="请输入资源ID" />
      </FormItem>

      <FormItem label="能力类型" name="capabilityId">
        <Select
          v-model="formData.capabilityId"
          placeholder="请选择能力类型"
          @change="onCapabilityChange"
        >
          <SelectOption value="booking_capability">预订能力</SelectOption>
          <SelectOption value="payment_capability">支付能力</SelectOption>
          <SelectOption value="notification_capability">通知能力</SelectOption>
          <SelectOption value="report_capability">报表能力</SelectOption>
        </Select>
      </FormItem>

      <FormItem label="状态" name="status">
        <Select v-model:value="formData.status" placeholder="请选择状态">
          <SelectOption value="enabled">启用</SelectOption>
          <SelectOption value="disabled">禁用</SelectOption>
        </Select>
      </FormItem>

      <FormItem label="配置信息" name="configuration">
        <div class="configuration-editor">
          <div class="config-tabs">
            <Tabs v-model:active-key="activeConfigTab">
              <TabPane key="basic" tab="基础配置">
                <div class="basic-config">
                  <FormItem
                    v-for="(value, key) in basicConfig"
                    :key="key"
                    :label="getConfigLabel(key)"
                  >
                    <Input
                      v-if="typeof value === 'string'"
                      v-model:value="basicConfig[key]"
                      :placeholder="`请输入${getConfigLabel(key)}`"
                    />
                    <InputNumber
                      v-else-if="typeof value === 'number'"
                      v-model:value="basicConfig[key]"
                      :placeholder="`请输入${getConfigLabel(key)}`"
                      style="width: 100%"
                    />
                    <Switch
                      v-else-if="typeof value === 'boolean'"
                      v-model:checked="basicConfig[key]"
                    />
                    <Select
                      v-else-if="Array.isArray(value)"
                      v-model:value="basicConfig[key]"
                      mode="multiple"
                      placeholder="请选择"
                    >
                      <SelectOption
                        v-for="option in getConfigOptions(key)"
                        :key="option"
                        :value="option"
                      >
                        {{ option }}
                      </SelectOption>
                    </Select>
                  </FormItem>
                </div>
              </TabPane>
              <TabPane key="advanced" tab="高级配置">
                <div class="advanced-config">
                  <Textarea
                    v-model:value="jsonConfig"
                    :rows="10"
                    placeholder="请输入JSON格式的配置信息"
                  />
                </div>
              </TabPane>
            </Tabs>
          </div>
        </div>
      </FormItem>
    </Form>

    <div class="modal-footer">
      <Button @click="handleCancel">取消</Button>
      <Button type="primary" @click="handleSubmit" :loading="submitting">
        确定
      </Button>
    </div>
  </Modal>
</template>

<style lang="less" scoped>
.configuration-editor {
  .config-tabs {
    .basic-config {
      .ant-form-item {
        margin-bottom: 16px;
      }
    }

    .advanced-config {
      .ant-input {
        font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        font-size: 12px;
        line-height: 1.5;
      }
    }
  }
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}
</style>
